import { ISkerMaster } from "./types";
import { createStorage, formatMinute, httpPost } from "./utils";

export abstract class SkerWorker {
    isRuning: boolean = false;
    hasRuning: boolean = false;
    master: ISkerMaster;
    thread: AutoJs.Thread;
    storage: AutoJs.Storage;
    constructor(master: ISkerMaster) {
        this.master = master;
        this.storage = createStorage();
    }
    // 开始
    start(): void {
        if (this.isRuning) return;
        if (this.hasRuning) return;
        this.log(`初始化完成`)
        home();
        this.isRuning = true;
        if (this.thread && this.thread.isAlive()) {
            this.thread.interrupt();
        }
        this.thread = threads.start(() => {
            this.log(`已启动`)
            sleep(1000)
            while (this.isRuning) {
                try {
                    this.run()
                    home();
                } catch (e) {
                    console.error(e)
                }
                this.sleep(5, '等待')
            }
            this.hasRuning = false;
            this.master.onStopSuccess()
            this.log(`已停止`)
        })
        this.thread.waitFor();
        this.master.onStartSuccess()
    }
    sleep(s: number = 5, text: string = `等待`) {
        const endTime = s * 1000 + new Date().getTime();
        while (new Date().getTime() < endTime) {
            sleep(1000)
            this.log(`${text}${formatMinute((endTime - new Date().getTime()) / 1000)}`)
        }
    }
    // 停止
    stop(): void {
        this.isRuning = false;
        this.log(`正在停止脚本...`)
    }
    abstract clear(): void;
    abstract run(): void;
    abstract onInit(): void;
    log(msg: string) {
        this.master.update(msg)
    }
    tryPost(path: string, body: any, def: any = {}) {
        try {
            return httpPost(path, body, false)
        } catch (e) {
            console.error(`http post error: ` + e?.toString())
            this.log(`网络或服务器错误`)
            return def;
        }
    }
}